package application.services;

import application.exceptions.ItemNotFoundException;
import application.model.modify.CountryModel;
import dao.CountryDao;
import mappings.Country;
import org.hibernate.exception.ConstraintViolationException;

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("countries")
public class CountryService
{
    private CountryDao countryDao = new CountryDao();

    @Path("addCountry")
    @POST
    @Produces(MediaType.APPLICATION_XML)
    public CountryModel addNewCountry(@FormParam("name") String name)
    {
        CountryModel countryModel = new CountryModel();

        try
        {
            Country country = countryDao.addCountry(name);
            countryModel.setId(country.getId());
            countryModel.setName(country.getName());
            countryModel.setStatus(0);
        }
        catch (ConstraintViolationException e)
        {
            // lapiemy wyjatek rzucany przez hibernate'a dla unique constraint - ustawiamy status 1 (rekord istnieje)
            countryModel.setStatus(1);
        }
        catch (Exception e)
        {
            // lapiemy wszystkie inne exceptiony i ustawiamy status na 2 (czyli cos sie wyjebalo, ale nie wiadomo co :P)
            countryModel.setStatus(2);
        }

        return countryModel;
    }

    @Path("editCountry")
    @POST
    @Produces(MediaType.APPLICATION_XML)
    public CountryModel editCountry(@FormParam("id") Integer id, @FormParam("name") String name)
    {
        CountryModel countryModel = new CountryModel();

        try
        {
            Country country = countryDao.editCountry(id, new Country(name));
            countryModel.setName(country.getName());
            countryModel.setId(country.getId());
            countryModel.setStatus(0);
        }
        catch (ItemNotFoundException e)
        {
            countryModel.setStatus(1); // 1 = nie znaleziono rekordu o danym id
        }
        catch (Exception e)
        {
            countryModel.setStatus(2);
        }

        return countryModel;
    }

    @Path("deleteCountry")
    @POST
    @Produces(MediaType.APPLICATION_XML)
    public CountryModel deleteCountry(@FormParam("id") Integer id)
    {
        CountryModel countryModel = new CountryModel();

        try
        {
            countryDao.deleteCountry(id);
            countryModel.setStatus(0);
        }
        catch (ItemNotFoundException e)
        {
            countryModel.setStatus(1); // 1 = nie znaleziono rekordu o danym id
        }
        catch (Exception e)
        {
            countryModel.setStatus(2);
        }

        return countryModel;
    }
}
